// components/cart-button/cart-button.ts

import { eventBus } from "../../utils/util"

const app = getApp<IAppOption>()
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    product: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    quantity: 0
  },

  lifetimes: {
    attached(this: any) {
      const updateHandler = () => {
        if (!this.properties.product || !this.properties.product._id) {
          return
        }
        const productId = this.properties.product._id
        const item = app.globalData.cart.find((item: any) => item._id === productId)

        this.updateQuantity(item?.quantity ?? 0)
      }
      updateHandler()
      this.updateHandler = updateHandler
      eventBus.on('cartUpdated', updateHandler)
    },
    detached(this: any) {
      if (this.updateHandler) {
        eventBus.off('cartUpdated', this.updateHandler)
      }
    }
  },
  pageLifetimes: {
    show() {
      if (!this.properties.product || !this.properties.product._id) {
        return
      }
      const productId = this.properties.product._id
      const item = app.globalData.cart.find((item: any) => item._id === productId)

      this.updateQuantity(item?.quantity ?? 0)
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 更新商品数量
    updateQuantity(newQuantity: number) {
      if (!this.properties.product || !this.properties.product._id) {
        return
      }

      let cart = app.globalData.cart || []
      const product = this.properties.product as IProduct

      if (newQuantity <= 0) {
        cart = cart.filter((item: any) => item._id !== product._id)
      } else {
        const index = cart.findIndex((item: any) => item._id === product._id)
        if (index > -1) {
          if (cart[index].stock < newQuantity) {
            wx.showToast({
              title: '库存不足',
              icon: 'none'
            })
            newQuantity = cart[index].stock
          }
          cart[index].quantity = newQuantity
        } else {
          cart.push({
            ...product,
            quantity: newQuantity,
            selected: true
          })
        }
      }
      app.globalData.cart = cart
      wx.setStorageSync('cart', cart)

      // 只更新当前组件对应的商品数量
      this.setData({
        quantity: newQuantity
      })
      this.triggerEvent('cartchange', { product })
    },

    // 减少数量
    decreaseQuantity(e: WechatMiniprogram.TouchEvent) {
      const newQuantity = this.data.quantity - 1
      this.updateQuantity(newQuantity)
    },

    // 增加数量
    increaseQuantity(e: WechatMiniprogram.TouchEvent) {
      const newQuantity = this.data.quantity + 1
      this.updateQuantity(newQuantity)
    },

    // 处理输入框失焦事件
    onQuantityBlur(e: WechatMiniprogram.InputBlur) {
      this.updateQuantity(Number.parseInt(e.detail.value))
    }
  }
})